using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ByHand.Model;
using ByHand.Data;
using ByHand.Services.Interfaces;
using ByHand.Data.Interfaces;
using ByHand.Services.Code;

namespace ByHand.Services.Implements
{
    public class ProductService : RepositoryBase<Product>, IProductService
    {
        public ProductService(IDatabaseFactory DbFactory) : base(DbFactory) { }



        public List<Product> GetByPage(int page, int pagesize, out int total)
        {
            var list = from u in ByHandDB.Products
                       orderby u.ID descending
                       select u;
            int skip = (page - 1) * pagesize;
            total = list.ToList().Count;
            return list.Skip(skip).Take(pagesize).ToList();
        }

        public List<Product> GetByPageFilter(int page, int pagesize, out int total, string filter)
        {
            int skip = (page - 1) * pagesize;
            var list = (from d in ByHandDB.Products
                        where d.Title.Contains(filter) || d.ProductCode.Contains(filter)
                        orderby d.ID descending
                        select d);

            total = list.ToList().Count;
            var alist = list.ToList();
            return list.Skip(skip).Take(pagesize).ToList();
        }

        public Product MaintainProductImages(Product product, List<string> images, bool isAddorDel)
        {
            if (isAddorDel)
            {
                foreach (var item in images)
                {
                    product.ImagePath += item + ";";
                }
            }
            else
            {
                foreach (var item in images)
                {
                    var oldimage = Utility.CreateImageUrl(item, product.ID, 1) + ";";
                    var pimages = product.ImagePath;
                    if (!string.IsNullOrWhiteSpace(pimages) && pimages.Contains(oldimage))
                    {
                        product.ImagePath = pimages.Remove(pimages.IndexOf(oldimage), oldimage.Length);

                    }
                }

            }
            return product;
        }
        public Product GetActive()
        {
            return (from d in ByHandDB.Products
                    where d.IsActive
                    select d).FirstOrDefault();
        }
        public int CountGuuProduct(int ProviderID)
        {
            return (from d in ByHandDB.Products
                    where d.ProviderID == ProviderID && d.GuuID != 0 && d.GuuID != null
                    select d).Count();
        }
        public Product GetByGuuID(int guuID) {
            return (from d in ByHandDB.Products
                    where d.GuuID ==guuID
                    select d).FirstOrDefault();
        }
    }
}
